package com.zhugang.week01;

/**
 * @program algorithms
 * @description: setZeroes
 * @author: chanzhugang
 * @create: 2022/04/01 07:19
 */
public class SetZeroes {

    public static void main(String[] args) {
        SetZeroes zeroes = new SetZeroes();
        int[][] matrix = new int[][]{{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
        zeroes.setZero(matrix);

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.println(matrix[i][j]);
            }
            System.out.println("\n");
        }

    }

    /**
     * 零矩阵
     * 编写一种算法，M * N 矩阵中某个元素为0，将其所在行和列都清零
     * <p>
     * 0, 1, 2, 0           0, 0, 0, 0
     * 3, 4, 5, 2    ===>   0, 4, 5, 0,
     * 1, 3, 1, 5           0, 3, 1, 0
     * <p>
     * 时间复杂度O(n*m)
     * 空间复杂度O(n+m)
     */
    public void setZero(int[][] matrix) {
        // 把哪一行、哪一列要清空为0，用boolean[]记录下， 遍历矩阵，只要行或者列为0，将其设置为0
        int n = matrix.length;
        if (n == 0) return;
        int m = matrix[0].length;
        boolean[] zeroRows = new boolean[n];
        boolean[] zeroColumns = new boolean[m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (matrix[i][j] == 0) {
                    zeroRows[i] = true;
                    zeroColumns[j] = true;
                }
            }
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (zeroRows[i] || zeroColumns[j]) {
                    matrix[i][j] = 0;
                }
            }
        }
    }

}